package com.cfun.mylearn.Support.utils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.UUID;



import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;
;
import com.cfun.mylearn.Support.base.BaseApplication;

/**
 * 读取android的一些系统资源
 * 
 * @author Dean
 */
public abstract class ResourceReader {
	private static final String SP_NAME = Constants.SP_NAME;
	private static final String UUID_KEY = "UUID_KEY";
	private static final String EMPTY = "";

	public static class ScreenInfo {
		public int width;
		public int height;
		public float density;
		public int densityDpi;

		@Override
		public String toString() {
			return "ScreenInfo [width=" + width + ", height=" + height + ", density=" + density + ", densityDpi="
					+ densityDpi + "]";
		}

	}

	// 从sp读取数据
	public static Object readsp(Context context, String spName, String spKey) {
		SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
		return sp.getAll().get(spKey);
	}

	public static String readString(String spKey) {
		SharedPreferences sp = BaseApplication.getInstance().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
		return sp.getString(spKey, EMPTY);
	}

	public static int readInt(String spKey, int defValue) {
		SharedPreferences sp = BaseApplication.getInstance().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
		return sp.getInt(spKey, defValue);
	}

	public static long readLong(String spKey, long defValue) {
		SharedPreferences sp = BaseApplication.getInstance().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
		return sp.getLong(spKey, defValue);
	}

	public static String readString(Context context, String spName, String spKey) {
		SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
		return sp.getString(spKey, EMPTY);
	}

	public static Boolean readBoolean(String spKey) {
		SharedPreferences sp = BaseApplication.getInstance().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
		return sp.getBoolean(spKey, false);
	}

	public static Boolean readBoolean(String spKey, boolean defaultValue) {
		SharedPreferences sp = BaseApplication.getInstance().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
		return sp.getBoolean(spKey, defaultValue);
	}

	public static Boolean readBoolean(Context context, String spName, String spKey) {
		SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
		return sp.getBoolean(spKey, false);
	}

	// 获取网络类型
	public static String readNetworkType(Context context) {
		String networkType = null;
		if (NetUtils.isWifi(context)) {
			networkType = "WIFI";
		} else if (NetUtils.is3G(context)) {
			networkType = "3G";
		} else if (NetUtils.is2G(context)) {
			networkType = "2G";
		} else {
			networkType = "UNKONWN";
		}
		ELog.d("网络类型:" + networkType);
		return networkType;
	}

	// 获取运行商
	public static String readOperators(Context context) {
		String operatorName = null;
		// 返回唯一的用户ID;就是这张卡的编号神马的
		String IMSI = readIMSI(context);
		if (StringUtils.isEmpty(IMSI)) {
			return "没有手机卡";
		}
		// IMSI号前面3位460是国家，紧接着后面2位00 02是中国移动，01是中国联通，03是中国电信。
		if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {
			operatorName = "中国移动";
		} else if (IMSI.startsWith("46001")) {
			operatorName = "中国联通";
		} else if (IMSI.startsWith("46003")) {
			operatorName = "中国电信";
		}
		ELog.d("运营商:" + operatorName);
		return operatorName;
	}

	// 读取手机型号
	public static String readDeviceModel(Context context) {
		String phoneModel = Build.MODEL;
		ELog.d("手机型号:" + phoneModel);
		return phoneModel;
	}

	// 读取手机系统版本
	public static String readOSVersion() {
		// String os = android.os.Build.MODEL + ","
		// + android.os.Build.VERSION.SDK_INT + ","
		// + android.os.Build.VERSION.RELEASE;
		String os = Build.VERSION.RELEASE;
		ELog.d("系统版本:" + os);
		return os;
	}

	// 读取屏幕分辨率
	public static ScreenInfo readScreenInfo(Context context) {
		DisplayMetrics metrics = getDisplay(context);
		ScreenInfo screenInfo = new ScreenInfo();
		screenInfo.width = metrics.widthPixels;
		screenInfo.height = metrics.heightPixels;
		screenInfo.density = metrics.density;
		screenInfo.densityDpi = metrics.densityDpi;
		return screenInfo;
	}

	public static DisplayMetrics getDisplay(Context context) {
		DisplayMetrics metrics = new DisplayMetrics();

		WindowManager WM = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		WM.getDefaultDisplay().getMetrics(metrics);
		return metrics;
	}

	// 读取软件系统版本号
	public static String readAppVersion(Context context) {
		String version = null;
		// 获取packagemanager的实例
		PackageManager packageManager = context.getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo;
		try {
			packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
			version = packInfo.versionName;
		} catch (NameNotFoundException e) {
			ELog.e("ResourceReader：readVersion:" + e.getMessage());
		}
		return version;
	}

	public static String readAppVersion() {
		return readAppVersion(BaseApplication.getInstance());
	}

	public static int readAppVersionCode() {
		int versionCode = 0;
		// 获取packagemanager的实例
		PackageManager packageManager = BaseApplication.getInstance().getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo;
		try {
			packInfo = packageManager.getPackageInfo(BaseApplication.getInstance().getPackageName(), 0);
			versionCode = packInfo.versionCode;
		} catch (NameNotFoundException e) {
			ELog.e("ResourceReader：readVersion:" + e.getMessage());
		}
		return versionCode;
	}

	// 读取手机的MAC地址
	public static String readMacAddress(Context context) {
		WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		String macAddress = info.getMacAddress();
		ELog.d(macAddress);
		return macAddress;
	}

	/*
	 * 读取手机相关信息 文档地址:http://developer.android.com/reference/android/telephony/
	 * TelephonyManager.html
	 * 获取实例方法:Context.getSystemService(Context.TELEPHONY_SERVICE)
	 */
	// 读取IMSI号码
	public static String readIMSI(Context context) {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String IMSI = tm.getSubscriberId();
		ELog.d("IMSI:" + IMSI);
		return IMSI;
	}

	public static String readSerial() {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
			return readRoSerialno();
		} else {
			return Build.SERIAL;
		}
	}

	public static String readRoSerialno() {
		String serialnum = "";
		try {
			Class<?> c = Class.forName("android.os.SystemProperties");
			Method get = c.getMethod("get", String.class, String.class);
			serialnum = (String) (get.invoke(c, "ro.serialno", "unknown"));
		} catch (Exception ignored) {
		}
		return serialnum;
	}

	// 读取手机的IMEI号码 IMEI=DEVICE_ID
	public static String readIMEI(Context context) {
		return readDeviceId(context);
	}

	/**
	 * 获取设备唯一标识码
	 * 
	 * @return
	 */
	public static String getUuid() {
		String deviceId = readDeviceId();
		String serialNo = readSerial();
		if (StringUtils.isNotEmpty(serialNo)) {
			serialNo += "-SERO";
		}
		String uuid = deviceId + serialNo;
		if (StringUtils.isEmpty(uuid)) {
			uuid = ResourceReader.readUuid() + "-UUID";
		}
		// 判断是否是模拟器
		String devicesUuid = EncodeUtils.encodeMD5Hex(uuid);
		if (isEmulator()) {
			return "EMU-" + devicesUuid;
		} else {
			return "NOR-" + devicesUuid;
		}
	}

	private static boolean isEmulator() {
		String android_id = Settings.Secure.getString(BaseApplication.getInstance().getContentResolver(), Settings.Secure.ANDROID_ID);
		boolean emulator = TextUtils.isEmpty(android_id) || "google_sdk".equals(Build.PRODUCT)
				|| "sdk".equals(Build.PRODUCT);
		return emulator;
	}

	public static String readUuid() {
		String uuid = ResourceReader.readString(UUID_KEY);
		if (StringUtils.isEmpty(uuid)) {
			uuid = UUID.randomUUID().toString();
			ResourceWrite.write2sp(UUID_KEY, uuid);
		}
		return uuid;
	}

	// 读取手机的设备ID IMEI=DEVICE_ID
	private static String readDeviceId(Context context) {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String deviceId = tm.getDeviceId();
		if (StringUtils.isEmpty(deviceId)) {
			deviceId = readMacAddress(context);
			if (!StringUtils.isEmpty(deviceId)) {
				deviceId += "-MAC";
			}
		} else {
			// 添加标记
			deviceId += "-DEVI";
		}
		return deviceId;
	}

	private static String readDeviceId() {
		return readDeviceId(BaseApplication.getInstance());
	}

	// 读取androidmainfest.xml文件里meta-data的值,注意这里的meta-data的父元素是application
	public static String readMetaString(String metaKey) {
		ApplicationInfo info = null;
		try {
			info = BaseApplication.getInstance().getPackageManager().getApplicationInfo(
					BaseApplication.getInstance().getPackageName(), PackageManager.GET_META_DATA);
			if (info.metaData != null && !StringUtils.isEmpty(info.metaData.getString(metaKey))) {
				return info.metaData.getString(metaKey);
			}
		} catch (NameNotFoundException e) {
			ELog.e("ResourceReader：readMeta:" + e.getMessage());
		}
		return "";
	}

	public static String readAssets(Context context, String fileName) {
		String content = "";
		try {
			InputStream is = context.getAssets().open(fileName);
			content = org.apache.commons.io.IOUtils.toString(is, "UTF-8");
		} catch (IOException e) {
			ELog.e(e.getMessage());
		}
		return content;
	}

	public static DisplayMetrics readDisplayMetrics(Activity activity) {
		DisplayMetrics metric = null;
		if (activity != null) {
			metric = new DisplayMetrics();
			activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
			// ELog.d("屏幕高度:" + metric.heightPixels);
			// ELog.d("屏幕宽度:" + metric.widthPixels);
			// ELog.d("屏幕密度:" + metric.density);
			// ELog.d("屏幕密度DPI:" + metric.densityDpi);
		}
		return metric;
	}

}
